import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:icooker/configs/mock_datas.dart';
import 'package:icooker/model/reommend_data.dart';
import 'package:icooker/pages/home/content/channel_list.dart';
import 'package:icooker/pages/home/content/home_banner.dart';
import 'package:icooker/providers/home_provider.dart';
import 'package:icooker/widgets/video_thumb.dart';
import 'package:kasax/commons/commons.dart';
import 'package:provider/provider.dart';

import 'appbar/appbar.dart';
import 'content/scan_list.dart';

/// 终版: 首页
class FinalPageHome extends StatefulWidget {
  const FinalPageHome({Key? key}) : super(key: key);

  @override
  _FinalPageHomeState createState() => _FinalPageHomeState();
}

class _FinalPageHomeState extends State<FinalPageHome>
    with AutomaticKeepAliveClientMixin {
  var provider = HomeProvider();

  @override
  void initState() {
    super.initState();
    provider.featchRecommends2();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: MyAppbar(),
      body: ChangeNotifierProvider(
        create: (_) => provider,
        child: HomeContent(),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class HomeContent extends StatefulWidget {
  const HomeContent({Key? key}) : super(key: key);

  @override
  _HomeContentState createState() => _HomeContentState();
}

class _HomeContentState extends State<HomeContent>
    with TickerProviderStateMixin {
  List<String> _homeTabList = ["推荐", "时令", "食肉", "素食", "烘焙"];

  late TabController _controller;

  @override
  void initState() {
    _controller = TabController(
        length: _homeTabList.length, vsync: this, initialIndex: 0);
    super.initState();
    print("_HomeContentState initState...");
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Consumer<HomeProvider>(
      builder: (context, provider, dhild) {
        return buildCustomScrollView(provider.getHomeList);
      },
      // child: , 不需要刷新的控件
    );
  }

  Widget buildCustomScrollView(List<RecommendData> dataList) {
    if (dataList != null && dataList.isNotEmpty) {
      return CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Container(
              color: Colors.white,
              margin: EdgeInsets.only(left: 10, right: 10),
              child: Column(
                children: [
                  buildVideoContainer(dataList[1]!.videoInfo!),
                  SizedBox(
                    height: 10,
                  ),
                  buildChannelGridView(dataList[2]!.channel!),
                  SizedBox(
                    height: 10,
                  ),
                  MeasList(dataList[3]!.sancan!),
                  SizedBox(
                    height: 10,
                  ),
                  buildBannerContainer(dataList[4]!.zhuanti!),
                  SizedBox(
                    height: 10,
                  ),
                ],
              ),
            ),
          ),

          // 推荐,时令，食肉，素食，烘焙 （5个栏目)
          buildSliverPersistentHeader(),
          buildSliverFillRemaining()
        ],
      );
    }
    return Container(
      child: buildLoadingWidget(),
    );
  }

  SliverFillRemaining buildSliverFillRemaining() {
    return SliverFillRemaining(
      child: TabBarView(
        controller: _controller,
        children: _homeTabList
            .map((e) => ListView.separated(
                itemBuilder: (context, index) {
                  return Container(
                    height: 80,
                    color: Colors.primaries[index],
                    child: Center(
                      child: Text("Item-$e - $index"),
                    ),
                  );
                },
                separatorBuilder: (context, index) {
                  return Divider();
                },
                itemCount: Colors.primaries.length))
            .toList(),
      ),
    );
  }

  SliverPersistentHeader buildSliverPersistentHeader() {
    return SliverPersistentHeader(
        // pinned: true,
        delegate: MyTabbarPersistentHeaderDelegate(
            child: TabBar(
      indicatorColor: Colors.transparent,
      labelColor: Colors.black,
      unselectedLabelColor: Colors.grey,
      labelStyle: TextStyle(fontSize: 16, color: Colors.black),
      controller: _controller,
      tabs: _homeTabList
          .map((e) => Text(
                e,
              ))
          .toList(),
    )));
  }

  Widget buildBannerContainer(List<Zhuanti> list) {
    return HomeBanner(list!);
  }

  SizedBox buildBannerSizedBox() {
    return SizedBox(
      height: 200,
      child: Swiper(
        autoplay: true,
        control: SwiperControl(),
        loop: true,
        pagination: new SwiperPagination(alignment: Alignment.bottomCenter),
        itemBuilder: (context, index) {
          return Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                    fit: BoxFit.cover,
                    image: NetworkImage(
                      GUIDE_IMAGE_LIST[index],
                    ))),
          );
        },
        itemCount: GUIDE_IMAGE_LIST.length,
        layout: SwiperLayout.DEFAULT,
      ),
    );
  }

  Widget buildChannelGridView(List<Channel> list) {
    return ChannelList(list);
  }

  Container buildVideoContainer(List<VideoInfoData> videoInfos) {
    if (videoInfos == null || videoInfos.isEmpty) {
      return Container(
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }
    return Container(
      height: 300,
      width: double.infinity,
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return Container(
            margin: EdgeInsets.only(left: index != 0 ? 10 : 0),
            child: SizedBox(
              height: 300,
              width: 210,
              child: VideoThumb(videoInfos[index]),
            ),
          );
        },
        itemCount: videoInfos.length,
      ),
    );
  }
}

class MyTabbarPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  MyTabbarPersistentHeaderDelegate({required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      padding: EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(
          image: DecorationImage(
              fit: BoxFit.fill, image: AssetImage('assets/images/bar03.png'))),
      child: child,
    );
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      true;
}

/// maxExtent 和minExtent 表示最大和最小值，滚动的时候高度在这个范围内变化。
/// shouldRebuild 表示是否需要更新，如果内容需要变化需要设置为true。
class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.blue,
      alignment: Alignment.center,
      child: Text(
        '我是一个SliverPersistentHeader',
        style: TextStyle(color: Colors.white),
      ),
    );
  }

  @override
  double get maxExtent => 200.0;

  @override
  double get minExtent => 100.0;

  // 如果内容需要更新，设置为true
  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      false;
}
